const router = require('koa-router')()
const GOODS = require('../models/goods')
const auth = require("../utils");
const path = require("path");


// 新增
router.post('/', auth, async function (ctx, next) {
    ctx.body = await GOODS.create(ctx.request.body)
})

//上次商品图片
router.post('/uploads', auth,async (ctx,next)=>{
    const file = ctx.request.files.file
    if(file.length){
        let imgArr = []
        file.map(item=>{
            imgArr.push( `${ctx.origin}/uploads/${path.basename(item.newFilename)}`)
        })
        console.log('上传图片', ctx.origin,imgArr)
        ctx.body = imgArr
    }else {
        console.log(`${ctx.origin}/uploads/${path.basename(file.newFilename)}`)
        ctx.body = [`${ctx.origin}/uploads/${path.basename(file.newFilename)}`]
    }
})

//查询
router.get('/', async function (ctx, next) {
    ctx.body = await GOODS.find()
})

//搜索商品
router.get('/query/:msg', async function (ctx, next) {
    ctx.body = await GOODS.find({title:new RegExp(ctx.params.msg,'ig')})
})

// 修改
router.put('/:id', auth, async function (ctx, next) {
    ctx.body = await GOODS.findByIdAndUpdate(ctx.params.id,ctx.request.body)
})

// 删除
router.delete('/:id', auth, async function (ctx, next) {
    ctx.body = await GOODS.findByIdAndDelete(ctx.params.id)
})


module.exports = router
